<template>
  <div class="app-container">
    <div class="app-container-header">
      <el-button icon="el-icon-back" circle @click="$router.go(-1)"></el-button>
      <el-button type="primary" icon="el-icon-plus" circle @click="handleNodeClick"></el-button>
      <el-button size="mini" icon="el-icon-delete" @click="handleMoreDelete">批量删除</el-button>
    </div>
    <div class="app-container-main">
      <el-table v-loading="loading" ref="tableRef" :data="planList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="节点名称" align="center" prop="itemName" />
        <!-- <el-table-column label="类路径" align="center" prop="address" /> -->
        <el-table-column label="地址" align="center" prop="accessLevel" >
          <template slot-scope="scope">
            {{ 'ns='+scope.row.ns+',i='+scope.row.identifier}}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" />
        <!-- <el-table-column label="访问权限" align="center" prop="accessLevel" >
          <template slot-scope="scope">
            <el-tag v-show="scope.row.accessLevel==1">Read only </el-tag>
            <el-tag v-show="scope.row.accessLevel==3" type="success">Write/Read</el-tag>
          </template>
        </el-table-column> -->
        <el-table-column label="节点数据类型" align="center" prop="type" />
        <el-table-column label="值" align="center" prop="val" />
          <!-- <template slot-scope="scope">
            <el-tag type="success">{{scope.row.val}}</el-tag>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <!-- <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
            >修改</el-button> -->
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      /> -->
    </div>

    <el-dialog v-loading="loading1" :title="title" :visible.sync="dialogVisible" width="400px" height="500px">
      <el-scrollbar style="height: 400px;">
        <el-tree
          v-loading="loading1"
          ref="treeRef"
          :data="data"
          show-checkbox
          accordion
          node-key="address"
          :props="defaultProps">
        </el-tree>
      </el-scrollbar>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAdd">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import {
  getBrowerNodes,
  nodeListMnitor,
  getNodeMnitorDeviceInfo,
  addMoreNodeMnitor,
  addNodeMnitor,
  putNodeMnitor,
  delNodeMnitor,
  getBatchValues,
} from "@/api/mes/dv/communication";

export default {
  name: "index",
  components: {},
  data() {
    return {
      loading: true,
      loading1: true,
      planList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 999,
        deviceMonitorId: this.$route.query.id,
      },
      title:'',
      dialogVisible:false,
      data: [],
      total: 0,
      defaultProps: {
        children: 'children',
        label: 'id'
      },
      arr:[],
      timer: null,
      ids: []
    }
  },
  created() {
    this.getList()
  },
  mounted() {
    // this.timer = setInterval(async() => {
    //   let ids = []
    //   this.planList.forEach(item=>{
    //     ids.push(item.deviceMonitorItemId)
    //   })
    //   if(ids.length == 0) return clearInterval(this.timer)
    //   const res = await getBatchValues(ids)
    //   // this.planList.forEach((item,ind)=>{
    //   //   this.$set(item,'val', res.data[ind])
    //   // })
    //   this.planList = res.data
    //   this.total = res.total
    // }, this.$route.query.cycle)
    if(this.$route.query.enabled=='true'){
      this.loopFun()
    }
  },
  beforeDestroy(){
    clearInterval(this.timer)
  },
  methods: {
    loopFun(){
      this.timer = setInterval(async() => {
        let ids = []
        this.planList.forEach(item=>{
          ids.push(item.deviceMonitorItemId)
        })
        if(ids.length == 0) return clearInterval(this.timer)
        const res = await getBatchValues(ids)
        // this.planList.forEach((item,ind)=>{
        //   this.$set(item,'val', res.data[ind])
        // })
        // this.planList = res.data
        this.planList.forEach(item=>{
          for (const iterator of res.data) {
            if((item.ns+item.identifier)==(iterator.ns+iterator.identifier)){
              this.$set(item,'val', iterator.val)
            }
          }
        })
        this.total = res.data.length
      }, this.$route.query.cycle)
    },
    async getList(){
      const res = await nodeListMnitor(this.queryParams)
      if(res.code == 200){
        this.planList = res.rows
        this.total = res.total
        this.loading = false
      }
      // console.log('getList');
    },
    handleUpdate(){
      this.title = '修改'
      this.dialogVisible = true
      console.log('handleUpdate');
    },
    handleDelete(row){
      this.$confirm('是否确认删除名称为"' + row.itemName + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delNodeMnitor(row.deviceMonitorItemId);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
      console.log('handleUpdate');
    },
    async handleAdd(){
      const res = this.$refs.treeRef.getCheckedKeys()
      this.handleFun(this.data, res)
      const res1 = await addMoreNodeMnitor(this.arr)
      if(res1.code == 200){
        this.$modal.msgSuccess("添加成功");
        this.dialogVisible = false
        this.getList()
        this.loopFun()
      }
    },
    // 递归处理树结构
    handleFun(data, res){
      data.forEach(item => {
        if(res.includes(item.address)&&item.dataType&&item.parentId){
          this.arr.push({
            deviceMonitorId: this.$route.query.id,
            itemName: item.id,
            type: item.dataType,
            accessLevel: item.accessLevel,
            identifier: item.identifier,
            ns: item.ns,
          })
        }
        if(item.children.length>0){
          this.handleFun(item.children, res)
        }
      });
    },
    async handleNodeClick() {
      this.title = '新增'
      this.dialogVisible = true
      const res = await getBrowerNodes(this.$route.query.id)
      if(res.code==200){
        this.loading1 = false
        this.data = res.data
      }
    },
    // 批量删除
    handleMoreDelete(){
      const that = this
      this.$confirm('是否确认删除数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delNodeMnitor(that.ids);
        }).then(() => {
          this.getList();
          this.$refs.tableRef.clearSelection();
          this.$modal.msgSuccess("删除成功");
        })
    },
    handleSelectionChange(val){
      this.ids = val.map(item => item.deviceMonitorItemId)
      // console.log(this.ids);
    }
  },
}
</script>

<style lang="scss" scoped>
::v-deep .el-scrollbar__bar.is-horizontal {
  display: none;
}
::v-deep .el-scrollbar__wrap {
  overflow-x: hidden;
  height: 100%;
}
.app-container{
  &-header{
    margin-bottom: 10px;
  }
}
</style>